package com.heisen.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heisen.base.exception.RRException;
import com.heisen.base.utils.MyObjectUtils;
import com.heisen.system.dto.UserRoleDto;
import com.heisen.system.entity.UserRole;
import com.heisen.system.mapper.UserRoleMapper;
import com.heisen.system.service.IUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author sen
 * @since 2023-12-24
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    /**
     * 新增 用户和角色关联
     * @param userRoleDto
     * @return
     */
    @Override
    @Transactional
    public Boolean addSysUserRole(UserRoleDto userRoleDto) {
        if(CollectionUtils.isEmpty(userRoleDto.getRoleId())) throw new RRException("角色id为空");
        ArrayList<UserRole> sysUserRoleList = new ArrayList<>();

        userRoleDto.getRoleId().forEach(
                o -> sysUserRoleList.add(new UserRole().setUserId(userRoleDto.getUserId()).setRoleId(o) )
        );
        return this.saveBatch(sysUserRoleList);
    }

    /**
     * 修改 用户和角色关联
     * @param userRoleDto
     * @return
     */
    @Override
    @Transactional
    public Boolean updateSysUserRole(UserRoleDto userRoleDto) {
        if(CollectionUtils.isEmpty(userRoleDto.getRoleId())) throw new RRException("角色id为空");

        // 删除用户和角色关联
        QueryWrapper<UserRole> wqSUR = new QueryWrapper<>();
        wqSUR.eq(UserRole.USER_ID,userRoleDto.getUserId());
        this.remove(wqSUR);
        return   addSysUserRole(userRoleDto);
    }


    /**
     * 查出 用户的所有角色
     * @param userId
     * @return
     */
    @Override
    public List<UserRole> selectAllUserRole(Long userId){
        if(MyObjectUtils.isEmpty(userId)) throw new  RRException("userid 为空");
        QueryWrapper<UserRole> wqSUR = new QueryWrapper<>();
        wqSUR.eq(UserRole.USER_ID,userId);
        return this.baseMapper.selectList(wqSUR);
    }

    @Override
    public boolean isuUseRoler(Long roleId) {
        QueryWrapper<UserRole> wq = new QueryWrapper<>();
        wq.eq(UserRole.ROLE_ID,roleId);
        Integer integer = this.baseMapper.selectCount(wq);
        if(integer > 0)  return true;
        return false;
    }
}
